import React, { Component } from 'react';
import {
  View,
  Text,
  TextInput,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  DeviceEventEmitter,
  Platform,
} from 'react-native';
import DatePicker from 'react-native-datepicker';
import PxToDp from '../../../utils/PxToDp';
import NavCon from '../../Public/NavCon';
import PersonalInfo from '../../../containers/PersonInfoContainer';
import FontFamilys from '../../../utils/FontFamilys';

import { submitDriveBill } from '../../../actions/communicateAction';
/* global ws */

class TestDriveBill extends Component {
  constructor(props) {
    super(props);

    this.state = {
      driveTime: this._getDateTime(),
      place: '',
      reception: '',
      note: '1. 了解大致行车路线，要做到心中有数;',
    };
  }
  _goBack() {
    this.props.navigator.pop();
  }

  _onDriveTimeChange(driveTime) {
    this.setState({ driveTime });
  }

  _submit() {
    if (!ws) {
      DeviceEventEmitter.emit('showToast', '客户连接已断开');
      return;
    }

    const { carInfo, dispatch } = this.props;
    const data = {};
    data.car = carInfo.car.modeldesc;
    data.car_id = carInfo.user.car_id;
    data.num = '1';
    data.phone = carInfo.user.phone;
    DeviceEventEmitter.emit('showToast', '客户连接已断开');
    data.place = this.getPickPlace();
    data.reception = this.getReception();
    data.username = carInfo.user.username;

    dispatch(submitDriveBill(data, (res) => {
      if (res.ret) {
        if (ws) {
          const send = res.testdrive;
          send.item14 = this.state.note;
          ws.send(JSON.stringify({ testdrive: JSON.stringify(send) }));
          DeviceEventEmitter.emit('showToast', '试驾表单发送成功！');
          setTimeout(this.props.navigator.pop, 1000);
        }
      }
    }));
  }

  getPickPlace() {
    const { dealerInfo } = this.props;

    if (this.state.place) {
      return this.state.place;
    }
    return dealerInfo && dealerInfo.dealer && dealerInfo.dealer.address;
  }

  getReception() {
    const { dealerInfo } = this.props;
    if (this.state.reception) {
      return this.state.reception;
    }
    return dealerInfo && dealerInfo.saler && dealerInfo.saler.username;
  }

  _getDateTime() {
    const date = new Date();
    const year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let hour = date.getHours();
    let minute = date.getMinutes();
    if (month.toString().length === 1) {
      month = `0${month}`;
    }
    if (day.toString().length === 1) {
      day = `0${day}`;
    }

    if (hour.toString().length === 1) {
      hour = `0${hour}`;
    }
    if (minute.toString().length === 1) {
      minute = `0${minute}`;
    }

    return `${year}-${month}-${day} ${hour}:${minute}`;
  }

  render() {
    const { carInfo, dealerInfo } = this.props;
    const user = carInfo.user;
    const { car } = carInfo;
    const defaultPlace = dealerInfo && dealerInfo.dealer && dealerInfo.dealer.address;
    const defaultReception = dealerInfo && dealerInfo.saler && dealerInfo.saler.username;

    return (
      <View style={[styles.flex, styles.bgColor, styles.titleTop]}>
        <NavCon currentTitle="生成预约试驾单" bgColor="#fff" onPress={() => this._goBack()} />
        <ScrollView>
          <PersonalInfo
            user={user}
            car={car}
            dealerInfo={dealerInfo}
          />
          <View style={[styles.bookDate, styles.section]}>
            <View style={styles.titleBg}>
              <Text style={styles.sectionTitle}>预约日期</Text>
            </View>
            <View style={[styles.item, styles.top25, { paddingBottom: 0 }]}>
              <Text style={styles.itemTitle}>试驾时间</Text>
              <DatePicker
                style={{ width: PxToDp(150) }}
                date={this.state.driveTime}
                mode="datetime"
                format="YYYY-MM-DD HH:mm"
                confirmBtnText="确认"
                cancelBtnText="取消"
                showIcon={false}
                customStyles={{
                  dateIcon: {
                    top: 4,
                  },
                  dateText: {
                    marginLeft: PxToDp(0),
                    color: '#666',
                    fontSize: PxToDp(14),
                  },
                  dateInput: {
                    borderRadius: PxToDp(2),
                    height: PxToDp(28),
                    width: PxToDp(150),
                    borderWidth: 0,
                  },
                }}
                onDateChange={(datetime) => {
                  this.setState({ driveTime: datetime });
                }}
              />
            </View>
            <View style={[styles.item]}>
              <Text style={styles.itemTitle}>试驾地点</Text>
              <TextInput
                placeholder="请输入试驾地点"
                defaultValue={defaultPlace}
                style={[styles.itemContent]}
                onChangeText={place => this.setState({ place })}
              />
            </View>
            <View style={[styles.item]}>
              <Text style={styles.itemTitle}>试驾专员</Text>
              <TextInput
                placeholder="请输入试驾专员"
                defaultValue={defaultReception}
                style={[styles.itemContent]}
                onChangeText={reception => this.setState({ reception })}
              />
            </View>
          </View>
        </ScrollView>
        <TouchableOpacity
          activeOpacity={0.6}
          style={[styles.submitWrapper]}
          onPress={() => this._submit()}
        >
          <Text style={[styles.submit]}>发送至{user && user.username}</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  flex: {
    flex: 1,
  },
  bgColor: {
    backgroundColor: '#f8f8fb',
    alignItems: 'center',
  },
  section: {
    width: PxToDp(355),
    backgroundColor: '#fff',
    paddingTop: PxToDp(15),
    paddingLeft: PxToDp(14),
  },
  item: {
    flexDirection: 'row',
    alignItems: 'center',
    width: PxToDp(341),
    paddingBottom: PxToDp(10),
    marginBottom: PxToDp(12),

    borderStyle: 'solid',
    borderColor: '#ededed',
    borderBottomWidth: PxToDp(1),
  },
  itemTitle: {
    width: PxToDp(106),
    fontSize: PxToDp(14),
    color: '#666',
  },
  itemContent: {
    width: PxToDp(164),
    fontSize: PxToDp(14),
    color: '#666',
  },
  top25: {
    marginTop: PxToDp(25),
  },
  submitWrapper: {
    justifyContent: 'center',
    alignItems: 'center',
    width: '100%',
    height: PxToDp(50),
    backgroundColor: '#f15556',
  },
  submit: {
    color: '#fff',
    fontSize: PxToDp(16),
  },
  titleTop: {
    marginTop: Platform.OS === 'ios' ? 20 : 0,
  },
  sectionTitle: {
    color: '#000000',
    fontSize: PxToDp(15),
    fontFamily: FontFamilys(),
  },
  titleBg: {
    backgroundColor: '#f8f8f9',
    paddingLeft: PxToDp(10),
    justifyContent: 'center',
    height: PxToDp(38),
    marginTop: PxToDp(20),
  },
});

export default TestDriveBill;
